// page/tabBar/wheat/index.js
var app = getApp();
var util = app.util;
var http = app.http;//request url请求
var beginmaiUrl = app.http.set_paimaistartPost;//开始排麦接口
var interval = []; // 未排倒计时
var gethall_list_interval; //档期列表接口 定时器
var dingdingJK = app.http.dingdingPost       //接口  消息 
var check_role = app.http.check_rolePost      //接口    角色  role 1主持  2主播  3既不是主播也不是主持
var join_ting = app.http.creat_user_verifyPost        //接口  申请加入厅
var save_wx_mobile = app.http.save_wx_mobilePost   // 接口 保存用户手机号
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hallIndex:0,        //默认选择第一个
    hasLogin: false,     //false 未登录
    hall: [],         //顶部厅列表 
    hall_info: null,      // 选中的厅
    height_bar: null,     //除去导航栏页面的高度 px
    roles: 0,             //角色 0  3主播 2主持 1管理员
    riqi: util.curRiqi(),          //档期日期  
    gethall_list: null,  // 所在厅的档期  
    tabbarshow: true,      //显示底部导航
    gethall_loadding: true, //档期列表接口显示加载
    dingding:false,    //消息显示红点 true显示
    showJianDang:true,  //根据时间 建档显示
    scroolHeight:0,  //scroll-view的高度
    role_loadding: true,  //角色接口显示加载
    isZhidingka:false,//置顶卡是否显示
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //手机小黑条高度px
    let safeAreaBottom = (wx.getSystemInfoSync().screenHeight - wx.getSystemInfoSync().safeArea.bottom)
    this.setData({
      safeAreaBottom
    })
   

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var that = this
    setTimeout(function () {
      // 延迟获取是为了解决真机上 windowHeight 值不对的问题
      wx.getSystemInfo({
        success: function (e) {
          that.setData({
            system: e
          });
          //计算scroll 高度
        }
      });
    }, 500)

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    //固定顶部自定义导航栏 需要获取导航栏高度
    this.height_bar()
    //删除本地存储当前档期
    wx.removeStorageSync("dangqiInfo");

        //
        // wx.navigateTo({
        //   url: '/page/wheat/pages/anchor_vacancy/anchor_vacancy',
        // })


        // return;
    //登录
    if(wx.getStorageSync("userinfo")){
      that.loginJiekou();
    }else{ //未登录
      that.noLoginJiekou()
      //openid接口返回 数据
      app.getUserInfoCallback=res=>{
        if(wx.getStorageSync("userinfo")){
           //登录
           that.loginJiekou();
        }
      }
    }

    this.getScrollviewHeight()
  },
  /**
   * 已经登录 调用的接口
   */
  loginJiekou(){
      var that = this
      //登录状态
      that.setData({
        hasLogin:true
      })

      //获取厅列表
      that.hall_list(function(code,err){
          
      //获取角色
      if(wx.getStorageSync('hall_info')){
        that.setData({
          role_loadding:false //不显示加载框
        })
        that.getPaimai(function(code1,err1){});
      }

        //每5秒接口获取厅列表
        if(wx.getStorageSync('hall_info')){
          that.dingshiList();
        }

      })
               
  },
  /**
   * 未登录 
   */
  noLoginJiekou(){
    var that = this
    var hall_info = null  //当前厅
    //分享
    if(wx.getStorageSync('share')){
      if(wx.getStorageSync('hall_info')){
        hall_info = wx.getStorageSync('hall_info')
      }
    }

    that.setData({
      hasLogin:false,
      roles:0,
      hall:[],
      hall_info:hall_info,
    })

  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    //清除档期列表定时器
    clearInterval(gethall_list_interval);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(gethall_list_interval);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    return util.shareSet(this, "档期列表");
  },
 //厅列表
 gethallList(){
  var that = this
  that.hall_list(function(code,err){
    //成功 
    if(code){
      //获取角色
      that.setData({
        role_loadding:false
      })
      that.getPaimai(function(code1,err1){});
      //每5秒接口获取厅列表
      that.dingshiList();
    }else{
      //分享
      var hall_info = "";
      console.log("分享",wx.getStorageSync('share') , wx.getStorageSync('hall_info'));
      if(wx.getStorageSync('share') && wx.getStorageSync('hall_info')){
        hall_info = wx.getStorageSync('hall_info')
      }
      that.setData({
        roles:0,
        hasLogin:false,
        hall_info,
        hall:[]
      })
    console.log(err);        
    }
  });
 },

  /**
   * 登录
   */
  onLogin: function (e) {
    var that = this

    app.login(e, function (err, res) {
      if (!err) {
        //成功
        that.loginJiekou();
       
      } else {
        //失败
        console.log(err)
      }
    })
  },
  /*
   * 日期弹框
   */
  dateDialog: function () {
    var riqi = this.data.riqi
    var bottomDialog = this.selectComponent("#bottomDialog")
    //获取日期下标 
    var dateIndex = [];
    //接口获取年 
    bottomDialog._getYear(function (err, yearlist) {
      if (!err) {
        //接口月
        bottomDialog._getMonth(riqi[0], function (errr, monthlist) {
          if (!errr) {
            if(yearlist.length == 0 || monthlist.length == 0){
              wx.showToast({
                title: '无排麦',
                icon:'none'
              })  
              return;
            }
            dateIndex.push(yearlist.indexOf((riqi[0])));
            dateIndex.push(monthlist.indexOf(riqi[1]));
            dateIndex.push(parseInt(riqi[2]) - 1);
            //设置
            bottomDialog.setData({
              title: '日期选择',
              years: yearlist,
              months: monthlist,
              modelType: "date",
              dateIndex: dateIndex,
              hideFlag: false
            })
            bottomDialog.showModal();
          } else {
            console.log(errr);
          }
        })
      } else {
        console.log(err);
      }
    });

  },
  /*
   *大厅弹框 
   */
  choiseting(e) {
 

    var i = this.data.hallIndex;
    var n = this.selectComponent("#bottomDialog")
    var hall = [];
    var hallList = this.data.hall;
    hallList.forEach(function(item,index){
      hall.push(item.name);
    })
    
    if(hall.length == 0){
      wx.showToast({
        title: '暂无其他厅',
        icon:'none'
      })  
      return;
    }

    n.setData({
        title: "大厅选择",
        modelType: "timeduan",
        selectArray: hall,
        selectIndex: [i],
        hideFlag: !1
    }), n.showModal();

  },
  /*
   *大厅弹框 回调 
   */
  hallSure: function(t) {
    var hall = this.data.hall
    this.setData({
      hallIndex:t.detail.index,
      hall_info:hall[t.detail.index]
    }) 
    clearInterval(gethall_list_interval);//清除定时
    //本地缓存存厅
    this.setHallId();
    //加入角色认证
    this.getPaimai(function(code,err){});
    //定时
    this.dingshiList();
  },

  /*
   *  跳转至空位补排页面
   */
  kongbupaiUrl: function(e){
    var that =this;
    that.bindGetUserInfo(e,function(err,res){
       if(err){
        let index = e.currentTarget.dataset.index;
        var gethall_list = that.data.gethall_list;
        var dangqiInfo = that.data.gethall_list[index];
        wx.setStorageSync('dangqiInfo', dangqiInfo);

        wx.navigateTo({
          url: '../../wheat/pages/anchor_vacancy/anchor_vacancy'
        })

       }else{
        console.log(res);
      }
    })
  },
  /*
   *  跳转至已派页面 
   */
  yipaiUrl: function (e) {
    var that =this;
    that.bindGetUserInfo(e,function(err,res){
       if(err){
        let index = e.currentTarget.dataset.index;
        var gethall_list = that.data.gethall_list;
        var dangqiInfo = that.data.gethall_list[index];
        wx.setStorageSync('dangqiInfo', dangqiInfo);
        var roles = wx.getStorageSync('userinfo').roles

        //主持页面 ：小程序管理员 或 创建的主持人
        if (roles.indexOf("1") != -1 || (dangqiInfo["manager_id"] == that.data.uid)) {
          wx.navigateTo({
            url: '../../wheat/pages/main_daka/main_daka',
          })
        } else {
          //判断是不是主播
          that.check_roleJk(dangqiInfo.id, function (err, role) {
             if (!err){
               if ([1, 2].indexOf(role) > -1){
                 wx.navigateTo({
                   url: '../../wheat/pages/main_daka/main_daka',
                 })
               }else{
                 //主播
                 wx.navigateTo({
                   url: '../../wheat/pages/anchor_yipai/anchor_yipai',
                 })
               }
             }else{
               console.log(err);
             }
          })
        }
       }else{
        console.log(res);
      }
    })

  },
  /*
   *  跳转至未派页面  小程序管理员进 主持的未排页面
   */
  weipaiUrl: function (e) {
    var that =this;
    that.bindGetUserInfo(e,function(err,res){
       if(err){
          let index = e.currentTarget.dataset.index;
          var gethall_list = that.data.gethall_list;

          var dangqiInfo = that.data.gethall_list[index];
          wx.setStorageSync('dangqiInfo', dangqiInfo);
          //判断档期有没过期
          var time = that.data.riqi.join("/") + " " + dangqiInfo["endtime"]
          if (new Date().getTime() > util.riqiTime(time)) {
            wx.showToast({
              title: '过期',
              icon: "none"
            })
            return;
          }
            //主播页面
            wx.navigateTo({
              url: '../../wheat/pages/anchor_wei/anchor_wei'
            })
       }
    }) 
  },
  /*
   *  跳转至直播也页面中
   */
  zhiboUrl: function (e) {
    var that =this;
    that.bindGetUserInfo(e,function(err,res){
       if(err){
          let index = e.currentTarget.dataset.index;
          var dangqiInfo = that.data.gethall_list[index];

          wx.setStorageSync('dangqiInfo', dangqiInfo);
          var roles = wx.getStorageSync('userinfo').roles;

          if (roles.indexOf("1") != -1 || (dangqiInfo["manager_id"] == that.data.uid)) {
            wx.navigateTo({
              url: '../../wheat/pages/main_daka/main_daka',
            })
          } else {
            //判断是不是主播
            that.check_roleJk(dangqiInfo.id, function (err, role) {
              if (!err) {
                if ([1, 2].indexOf(role) > -1) {
                  wx.navigateTo({
                    url: '../../wheat/pages/main_daka/main_daka',
                  })
                } else {
                  //主播
                  wx.navigateTo({
                    url: '../../wheat/pages/anchor_yipai/anchor_yipai',
                  })
                }
              } else {
                console.log(err);
              }
            })
          }
        }else{
          console.log(res);
        }
      })
  },
  /*
   *  跳转至排麦中页面 
   */
  paimaizhongUrl: function (e) {
    var that =this;
    that.bindGetUserInfo(e,function(err,res){
       if(err){
          let index = e.currentTarget.dataset.index;
          var dangqiInfo = that.data.gethall_list[index];
          wx.setStorageSync('dangqiInfo', dangqiInfo);
          var roles = wx.getStorageSync('userinfo').roles;
          wx.navigateTo({
            url: '../../wheat/pages/anchor_paimaizhong/anchor_paimaizhong'
          })
        }else{
          console.log(res);
        }
      })
  },
  /*
 *  跳转至补排页面
 */
  bupaimaiUrl: function (e) {
    var that =this;
    that.bindGetUserInfo(e,function(err,res){
       if(err){
          let index = e.currentTarget.dataset.index;
          var dangqiInfo = that.data.gethall_list[index];
          wx.setStorageSync('dangqiInfo', dangqiInfo);
          var roles = wx.getStorageSync('userinfo').roles;
          wx.navigateTo({
            url: '../../wheat/pages/anchor_budang/anchor_budang'
          })
        }else{
          console.log(res);
        }
      })
  },
  //厅列表
  hall_list: function (callback) {

    var that = this
    var uid = wx.getStorageSync('userinfo').uid;
    if(!uid){
      callback(false)
    } 
    console.log("厅列表")
    http.hallListPost({
      uid: uid
    },false).then(res => {
      console.log(res,"厅列表接口")
      var hall = res.data;
      if (res.code == 0) {
        //分享追加厅
        let hallindex_flag = 0; //0 是厅列表不存在分享
        let sharehallinfo =  wx.getStorageSync('share').hall_info
        hall.forEach(function (item, index) {
          if(sharehallinfo && item.id == sharehallinfo["id"]){
            hallindex_flag = 1
          }
        })
        if(hallindex_flag == 0 && sharehallinfo){
          hall.push(sharehallinfo)
        }
        //设置当前选中的厅，默认选中第一个厅
        let hallindex = 0;//记录当前厅的下标
        var hall_info = wx.getStorageSync('hall_info');
        console.log("wx.getStorageSync('hall_info'):",hall_info,"hall：",hall_info);
        hall.forEach(function (item, index) {
          if (hall_info && item.id == hall_info["id"]) {
            hallindex = index  
          }
        })

        that.setData({
          hall:hall,
          hall_info:hall.length? hall[hallindex]:null
        })
        //存厅id
        that.setHallId();
        //成功返回
        callback(true)
      }else{
        //失败返回00
        callback(false,res)
      }
    })
  },

  //厅点击选择回调
  hallIndex: function (e) {
    
    clearInterval(gethall_list_interval);//清除定时
    var hall = this.data.hall;
    var hall_index = e.detail.index;
    this.setData({
      hall_info: hall[hall_index],
      role_loadding:false    //不显示提示信息
    })
    //本地缓存存厅
    this.setHallId();
    //加入角色认证
    this.getPaimai(function(code,err){

    });
    //定时
    this.dingshiList();
  },
  //本地缓存存厅
  setHallId: function () {
    var hall_info = this.data.hall_info;
    wx.setStorageSync('hall_info', hall_info);
  },
  //导航栏高度
  height_bar: function () {
    var navBar = this.selectComponent("#navBar")
    // console.log(navBar,"3333333333333333333")
    var status = navBar.data.status;
    var navHeight = navBar.data.navHeight;
    var screenHeight = navBar.data.screenHeight;//667
    var height_bar = screenHeight - (status + navHeight)
    //console.log(navBar, navHeight, screenHeight,"gao")
    this.setData({
      height_bar
    })
  },
  //加入角色认证
  getPaimai: function (callback) {
   
    //未登录
    if (!wx.getStorageSync('userinfo').token) {
      this.setData({
        hasLogin: false
      })
      return;
    }
    var that = this
    let role_loadding = that.data.role_loadding
    console.log(role_loadding,"角色");
    app.getRoles(function (sucess, msg, res) {
      console.log("角色接口返回数据res.status == 1是成功",res);
      console.log(wx.getStorageSync('userinfo'));
      if (sucess) {
        if (res.status == 1){
          //更新缓存角色
          let userinfo =  wx.getStorageSync('userinfo')
          userinfo.roles = res.roles;
          userinfo.nickname = res.nickname;
          wx.setStorageSync('userinfo', userinfo);

          var roles = res.roles + ''
          var roles_xcx = roles.indexOf("1") != -1 ? 1 : 0
          //成功
          that.setData({
            roles: res.roles,
            roles_xcx: roles_xcx,
            userinfo:userinfo,
            gethall_loadding:false,
          })
          console.log(that.data.gethall_loadding,"档期");
          // 获取所在厅的档期
          that.gethall_list();

          //获取所在厅的消息
          that.dingding();

          //设置置顶卡显示
          var hall_info =  wx.getStorageSync('hall_info')
          var flag = util.checkAuditTime(hall_info["send_start"],hall_info["send_end"]);
          that.setData({
            isZhidingka: flag
          })
          typeof callback == 'function' &&  callback(1)
        }else{
          //加入厅
          join_ting({
            token:wx.getStorageSync('userinfo').token,
            hall_id:wx.getStorageSync('hall_info').id
          },false).then(res => {
            if (res.code == 0) {
              let userinfo =  wx.getStorageSync('userinfo')
              userinfo.roles = 0;
              wx.setStorageSync('userinfo', userinfo);
              that.setData({
                roles: 0,                          //角色设置默认 未认证
                roles_xcx: 0,
              })
              if(role_loadding){
                wx.showToast({
                  title: '请联系管理员认证',
                  icon: 'none',
                  duration: 2000
                })
              }
              typeof callback == 'function' && callback(2)
            } else {
               console.log("加入失败");
               typeof callback == 'function' && callback(0,res)
            }
          }).catch(err => {
            console.log("服务器异常");
          })
        }  
      } else {
        typeof callback == 'function' && callback(0,res)
        //失败
        console.log('err:', res)
      }
    },role_loadding)
  },
  //接口 dingding
  dingding(){
    if(!wx.getStorageSync('userinfo').roles){
        return; 
    }
    var hall_id = wx.getStorageSync('hall_info').id
    var token = wx.getStorageSync('userinfo').token

    dingdingJK({
      token: token,
      hall_id
    }, false).then(re => {
      if (re.code == 0) {
        if (re.count){
          this.setData({
            dingding: true
          })
         }else{
          this.setData({
            dingding: false
          })
         }
      }else {
        wx.showToast({
          title: '获取数据失败',
          icon:'none'
        })
        console.log("dingdin接口返回数据失败", re);
      }
    })
  },
  // 获取所在厅的档期列表
  gethall_list: function () {
    var that = this
    if(!wx.getStorageSync('hall_info') ||  !wx.getStorageSync('userinfo')){
      return;
    }
    var hall_id = wx.getStorageSync('hall_info').id
    var token = wx.getStorageSync('userinfo').token
    var loadding = this.data.gethall_loadding
    var curriqi = that.data.riqi
    var riqi = curriqi[0] + '-' + curriqi[1] + '-' + curriqi[2];
    if (!hall_id || !token) {
      console.log("token不存咋或厅id不存咋")
      return;
    }

    http.dangqi_listPost({
      token: token,
      hall_id,
      date: riqi
    }, loadding).then(re => {
      if (re.code == 0) {
        var data = re.data1.concat(re.data2)
        that.setData({
          gethall_list: data,
          uid: re.uid
        })
        //未排:倒计时,自动开始排麦
        this.weiDaojishi();
        //
      } else if (re.code == -1) {
        that.setData({
          roles: 0,
          roles_xcx: 0
        })
        var userinfo = wx.getStorageSync('userinfo')
        userinfo.roles = 0
        wx.setStorageSync('userinfo', userinfo);
      } else {
        console.log("接口返回数据失败", re);
      }
    })
  },
  //设置日期
  riqiSure: function (e) {
    let riqi =  e.detail.join("/");
    if((new Date(riqi).getTime()+24*60*60*1000) >= new Date().getTime()){
      this.setData({
        showJianDang: 1
      })
    }else{
      this.setData({
        showJianDang: 0
      })
    }
     
    this.setData({
      riqi: e.detail
    })
    this.gethall_list()
  },
  // 小程序管理员 建档 页面
  jiandangUrl() {
    var riqi = this.data.riqi
    wx.navigateTo({
      url: '../../wheat/pages/xcx_jiandang/xcx_jiandang?riqi=' + riqi.join()
    })
  },
  //未排:倒计时,自动开始排麦
  weiDaojishi() {
    var gethall_list = this.data.gethall_list;
    for (var i = 0; i < gethall_list.length; i++) {
      //未排
      if (gethall_list[i]["status"] == 5) {
        //倒计时
        if (gethall_list[i]["daojishi"] > 0) {
          var daojishi_index = 'daojishi[' + i + ']'
          this.setData({
            [daojishi_index]: gethall_list[i].daojishi
          })
          clearInterval(interval[i])
          interval[i] = setInterval(function (i) {
            var num = (this.data.daojishi[i])
            if (num <= 0) {
              this.gethall_list();
              clearInterval(interval[i]);
            } else {
              var daojishi = 'daojishi[' + i + ']'
              this.setData({
                [daojishi]: num - 1
              })
            }
          }.bind(this, i), 1000)
        }
      }
    }
  },
  //开始排麦接口
  beginmai(did) {
    var that = this;
    var token = wx.getStorageSync('userinfo').token
    beginmaiUrl({
      did: did,
      token: token
    }).then(res => {
      if (res.code == 0) {
        that.gethall_list();
      } else {
        console.log("失败", res)
      }
    })
  },

  //角色接口
  check_roleJk(dangqi_id,callback) {
    var that = this;
    let token = wx.getStorageSync("userinfo").token
    let hall_id = wx.getStorageSync("hall_info").id
    let c_uid = wx.getStorageSync("userinfo").uid
    check_role({
      token,
      hall_id,
      c_uid,
      dangqi_id
    },false).then(function (n) {
      if (n.code == 0) {
        callback(null, n.role)
      } else {
        callback(n);
      }
    });
  },
  //保存用户手机号
  bindGetUserInfo (e,callback) {
      if(wx.getStorageSync('userinfo').mobile){
        callback(true);
        return;
      }
      if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
        wx.showToast({
          title: '未授权不能操作',
          icon:'none'
        })
        callback(false);
        return;
      }
      if(!app.globalData.openid){
        wx.showToast({
          title: 'openid不存在',
          icon:'none'
        })
        return;
      }
      if (e.detail.errMsg == "getPhoneNumber:ok") {
          save_wx_mobile({
            token: wx.getStorageSync('userinfo').token,
            encryptedData: e.detail.encryptedData,
            iv: e.detail.iv,
    //        code:app.globalData.code,
            openid:app.globalData.openid,
            session_key:app.globalData.session_key,
          }).then(re => {
            if (re.code == 0) {
             let userinfo =  wx.getStorageSync('userinfo')
             userinfo.mobile =  re.phone
             wx.setStorageSync('userinfo', userinfo);
              callback(true);
            } else {
              wx.showToast({
                title: '手机号获取失败 请重试',
                icon:'none'
              })
              callback(false,'保存失败')
            }
          })
    }else{
      callback(false);
      return;
    }
  },
  //获取scroolHeight 的高度
  getScrollviewHeight(){
    let that = this
    let getSystemInfoSync = wx.getSystemInfoSync()
    // 创建节点查询器 query
    let query = wx.createSelectorQuery();
    //获取 id= navBar
    query.select('#navBar').boundingClientRect()

  
    //计算
    query.exec((res) => {
      let navBarHeight =  res[0].height                                          //navBar
  
      let scroolHeight = getSystemInfoSync.windowHeight - navBarHeight 
      that.setData({
        scroolHeight
      })
    })
  },
  //定时每个5秒
  dingshiList:function(){
    if(wx.getStorageSync('userinfo').token && wx.getStorageSync('hall_info')){
      gethall_list_interval = setInterval(function () {
        this.setData({
          gethall_loadding: false
        })
        this.gethall_list()
      }.bind(this), 5000)
    }
  },
  //申请加入团队
  joinPaimai(){
    var that = this;
    if(!wx.getStorageSync('hall_info')){
        wx.showToast({
          title: '暂无厅可以申请',
          icon:'none'
        })
        return;
    }
    //显示提示框
    that.setData({
      role_loadding:true 
    })
    that.getPaimai(function(res,err){})
  }
})